package com.stedu.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stedu.bean.RespBean;
import com.stedu.bean.Student;
import com.stedu.exception.SteduException;
import com.stedu.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.List;


@CrossOrigin
@RestController
@RequestMapping("/admin/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Value("5")
    private Integer pageSize;
    @GetMapping("/selectByPage")
    public RespBean selectByPage(Integer PageNum, String sname,String sgender){
        if (PageNum==0){
            PageNum=1;
        }
        //currentPage开始页面
        PageHelper.startPage(PageNum,pageSize);
        //查询
        List<Student> studentList = studentService.selectBySname(sname,sgender);

        //封装分页
        PageInfo<Student> pageInfo = new PageInfo<>(studentList, 5);
        return RespBean.ok("成功",pageInfo);
    }
    //加
    @PostMapping("/insert")
    public RespBean insert(@RequestBody @Validated Student student) throws SQLException, SteduException {
        //添加
        if (studentService.insert(student)){
            return  RespBean.ok("添加成功~~~");
        }
        else {
            return RespBean.error("添加失败，请重新添加");
        }
    }
    //删
    @DeleteMapping("/{sid}")
    public RespBean delete(@PathVariable("sid") Integer sid) throws SteduException {
        //删除
        if (studentService.delete(sid)){
            return RespBean.ok("删除成功~~~");
        }else{
            return RespBean.error("删除失败，请重新添加");
        }

    }
    //改
    @PutMapping("/update")
    public RespBean update(@RequestBody @Validated Student student) throws SteduException {
        //修改
        if (studentService.update(student)){
            return RespBean.ok("修改成功~~~");
        }
        else {
            return RespBean.error("修改失败，请重新修改0.0");
        }
    }

    //查所有
    @GetMapping
    public RespBean selectAll(){
        List<Student> studentList = studentService.selectAll();
        return RespBean.ok("", studentList);
    }

    //根据sid查
    @GetMapping("/{sid}")
    public RespBean selectBySid(@PathVariable("sid") Integer sid){
        Student student = studentService.selectBySid(sid);
        return RespBean.ok("", student);
    }
}
